
from docx import Document
from docx.shared import Pt, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
from docx.oxml import OxmlElement
from docx.oxml.ns import qn

def extract_title_content(text, title_patterns):
    """提取标题内容和正文内容，遇到第一个句号就结束"""
    for pattern in title_patterns:
        if text.startswith(pattern):
            # 找到第一个句号的位置
            period_pos = text.find('。')
            if period_pos != -1:
                title_content = text[:period_pos + 1]  # 包含句号
                body_content = text[period_pos + 1:]   # 句号后的内容
                return title_content, body_content
            else:
                # 如果没有句号，整个段落都是标题
                return text, ""
    return None, text

def is_standalone_title(text, title_patterns):
    """判断是否为单独占一行的标题"""
    for pattern in title_patterns:
        if text.startswith(pattern):
            # 如果整个段落就是标题模式，或者标题后没有其他内容
            if text == pattern or len(text) <= len(pattern) + 2:
                return True
    return False

def add_page_number(paragraph):
    """添加页码字段，格式为 —页码—"""
    # 添加前一个破折号
    run1 = paragraph.add_run("—")
    run1.font.name = '宋体'
    run1._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
    run1.font.size = Pt(12)
    
    # 添加页码字段
    run2 = paragraph.add_run()
    run2.font.name = '宋体'
    run2._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
    run2.font.size = Pt(12)
    
    fld_char = OxmlElement('w:fldChar')
    fld_char.set(qn('w:fldCharType'), 'begin')
    run2._r.append(fld_char)
    
    instr_text = OxmlElement('w:instrText')
    instr_text.set(qn('xml:space'), 'preserve')
    instr_text.text = "PAGE"
    run2._r.append(instr_text)
    
    fld_char = OxmlElement('w:fldChar')
    fld_char.set(qn('w:fldCharType'), 'end')
    run2._r.append(fld_char)
    
    # 添加后一个破折号
    run3 = paragraph.add_run("—")
    run3.font.name = '宋体'
    run3._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
    run3.font.size = Pt(12)

def ensure_style(doc, style_name, font_name, font_size, is_center=False):
    """确保样式存在，不存在则创建"""
    try:
        style = doc.styles[style_name]
    except KeyError:
        style = doc.styles.add_style(style_name, 1)
    
    # 设置字体
    style.font.name = font_name
    style.font.size = Pt(font_size)
    style.font._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)
    
    # 设置段落格式
    if is_center:
        style.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    else:
        style.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
    
    style.paragraph_format.line_spacing_rule = WD_LINE_SPACING.EXACTLY
    style.paragraph_format.line_spacing = Pt(28.5)
    style.paragraph_format.space_before = Pt(0)
    style.paragraph_format.space_after = Pt(0)
    
    if not is_center:
        style.paragraph_format.first_line_indent = Cm(0.74)  # 2个字符缩进
    
    return style

def format_docx(input_file):
    doc = Document(input_file)
    
    # 设置页面
    section = doc.sections[0]
    section.page_width = Cm(21)    # 宽210mm
    section.page_height = Cm(29.7) # 高297mm
    section.top_margin = Cm(3.7)   # 上边距37mm
    section.bottom_margin = Cm(3.5) # 下边距35mm
    section.left_margin = Cm(2.8)  # 左边距28mm
    section.right_margin = Cm(2.6) # 右边距26mm
    
    # 定义标题模式
    level1_patterns = ['一、', '二、', '三、', '四、', '五、']
    level2_patterns = ['一是', '二是', '三是', '四是', '(一)', '（一）', '(二)', '（二）', '(三)', '（三）', '(四)', '（四）']
    
    # 处理第一行作为标题
    if doc.paragraphs:
        first_para = doc.paragraphs[0]
        if first_para.text.strip():
            # 设置标题样式
            title_style = ensure_style(doc, 'DocumentTitle', '方正小标宋', 22, True)
            first_para.style = title_style
            first_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
            first_para.paragraph_format.first_line_indent = Cm(0)
            
            # 在第一行后面插入空行
            doc.add_paragraph()
    
    # 处理其他段落
    for i, para in enumerate(doc.paragraphs):
        text = para.text.strip()
        if not text:
            continue
            
        # 跳过第一行（已经是标题）
        if i == 0:
            continue
            
        # 统一设置段落格式
        para.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY  # 两端对齐
        para.paragraph_format.line_spacing_rule = WD_LINE_SPACING.EXACTLY  # 固定行距
        para.paragraph_format.line_spacing = Pt(28.5)  # 行距28.5磅
        para.paragraph_format.space_before = Pt(0)  # 段前0
        para.paragraph_format.space_after = Pt(0)   # 段后0
        
        # 检查是否为一级标题
        title_content, body_content = extract_title_content(text, level1_patterns)
        if title_content or is_standalone_title(text, level1_patterns):
            if is_standalone_title(text, level1_patterns):
                # 单独占一行的标题
                para.clear()
                run = para.add_run(text)
                run.font.name = '黑体'
                run.font.size = Pt(16)
                run._element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')
                para.alignment = WD_ALIGN_PARAGRAPH.CENTER
                para.paragraph_format.first_line_indent = Cm(0)
            elif title_content:
                # 标题+正文的情况
                para.clear()
                # 添加标题部分
                title_run = para.add_run(title_content)
                title_run.font.name = '黑体'
                title_run.font.size = Pt(16)
                title_run._element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')
                # 添加正文部分
                if body_content.strip():
                    body_run = para.add_run(body_content)
                    body_run.font.name = '仿宋'
                    body_run.font.size = Pt(16)
                    body_run._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
                para.paragraph_format.first_line_indent = Cm(0.74)  # 正文缩进2字符
            continue
        
        # 检查是否为二级标题
        title_content, body_content = extract_title_content(text, level2_patterns)
        if title_content or is_standalone_title(text, level2_patterns):
            if is_standalone_title(text, level2_patterns):
                # 单独占一行的标题
                para.clear()
                run = para.add_run(text)
                run.font.name = '楷体'
                run.font.size = Pt(16)
                run._element.rPr.rFonts.set(qn('w:eastAsia'), '楷体')
                para.alignment = WD_ALIGN_PARAGRAPH.CENTER
                para.paragraph_format.first_line_indent = Cm(0)
            elif title_content:
                # 标题+正文的情况
                para.clear()
                # 添加标题部分
                title_run = para.add_run(title_content)
                title_run.font.name = '楷体'
                title_run.font.size = Pt(16)
                title_run._element.rPr.rFonts.set(qn('w:eastAsia'), '楷体')
                # 添加正文部分
                if body_content.strip():
                    body_run = para.add_run(body_content)
                    body_run.font.name = '仿宋'
                    body_run.font.size = Pt(16)
                    body_run._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
                para.paragraph_format.first_line_indent = Cm(0.74)  # 正文缩进2字符
            continue
        
        # 普通正文
        para.paragraph_format.first_line_indent = Cm(0.74)  # 缩进2字符
        
        # 设置字体
        for run in para.runs:
            run.font.name = '仿宋'
            run.font.size = Pt(16)
            run._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
    
    # 添加页码
    footer = section.footer
    paragraph = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
    paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    
    # 添加页码字段
    add_page_number(paragraph)

    doc.save(input_file)
    print(f"文档已格式化并保存: {input_file}")

if __name__ == "__main__":
    import sys
    if len(sys.argv) != 2:
        print("用法: python word.py 文件名.docx")
        sys.exit(1)
    format_docx(sys.argv[1])
